package meiyunting.shiwuzhaoling_gatway.filter;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

/**
 * Token验证过滤器
 */
@Slf4j
@Component
public class TokenCheckGatewayFilterFactory extends AbstractGatewayFilterFactory<TokenCheckGatewayFilterFactory.Config> {

    private static final String TOKEN_PREFIX = "Bearer ";
    private static final String AUTH_HEADER = "Authorization";

    public TokenCheckGatewayFilterFactory() {
        super(Config.class);
    }

    @Override
    public GatewayFilter apply(Config config) {
        return (exchange, chain) -> {
            ServerHttpRequest request = exchange.getRequest();
            ServerHttpResponse response = exchange.getResponse();

            // 获取请求路径
            String path = request.getURI().getPath();
            
            // 对于登录、注册等接口不需要验证token
            if (path.contains("/auth/login") || path.contains("/auth/register")) {
                return chain.filter(exchange);
            }

            // 获取token
            String token = getToken(request);
            if (StringUtils.isEmpty(token)) {
                log.error("Token不存在，请求路径：{}", path);
                return unauthorized(response, "Token不存在");
            }

            // 验证token (简单验证，实际项目中应该调用认证服务进行验证)
            if (!validateToken(token)) {
                log.error("Token无效，请求路径：{}", path);
                return unauthorized(response, "Token无效或已过期");
            }

            // 验证通过，继续执行后续过滤器
            return chain.filter(exchange);
        };
    }

    /**
     * 从请求头中获取Token
     */
    private String getToken(ServerHttpRequest request) {
        String token = request.getHeaders().getFirst(AUTH_HEADER);
        if (StringUtils.hasText(token) && token.startsWith(TOKEN_PREFIX)) {
            return token.substring(TOKEN_PREFIX.length());
        }
        return null;
    }

    /**
     * 验证Token
     * 实际项目中应该调用认证服务进行验证
     */
    private boolean validateToken(String token) {
        // 这里只是简单示例，实际项目中应该调用认证服务验证token
        return StringUtils.hasText(token) && token.length() > 10;
    }

    /**
     * 返回未授权响应
     */
    private Mono<Void> unauthorized(ServerHttpResponse response, String message) {
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        response.getHeaders().add(HttpHeaders.CONTENT_TYPE, "application/json;charset=UTF-8");
        
        Map<String, Object> result = new HashMap<>(3);
        result.put("code", HttpStatus.UNAUTHORIZED.value());
        result.put("message", message);
        result.put("data", null);
        
        String body = "{\"code\":401,\"message\":\"" + message + "\",\"data\":null}";
        DataBuffer buffer = response.bufferFactory().wrap(body.getBytes(StandardCharsets.UTF_8));
        return response.writeWith(Mono.just(buffer));
    }

    /**
     * 配置类
     */
    public static class Config {
        // 可以在这里添加配置属性
    }
} 